#include "addform.h"
#include "ui_addform.h"

#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMessageBox>


AddForm::AddForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AddForm)
{
    ui->setupUi(this);

    // 1. 给添加按钮设置信号和槽
    // 2. 槽函数
    //   1) 收集表单数据
    //   2) 使用post方式发送请求（根据接口文档），并将数据一起发送给服务器端
    //   3) 接收服务器端的返回结果，进行下一步处理
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);

    connect(manager, &QNetworkAccessManager::finished, [this](QNetworkReply *reply){
        QByteArray jsonStr = reply->readAll();
        QJsonObject jsonObj = QJsonDocument::fromJson(jsonStr).object();
        if (jsonObj.value("code").toInt() == 200)
        {
            // 添加成功后：关闭当前窗口  主窗口更新数据（向主窗口发送一个自定义信号）
            emit this->addOk();
            this->close();
        }
        else
        {
            qDebug() << jsonObj.value("msg").toString();
        }
    });

    connect(ui->pushButton, &QPushButton::clicked, [this, manager](){
        QString name = ui->nameLine->text();
        QString nickname = ui->nickLine->text();
        QString gender = ui->genderLine->text();
        QString age = ui->ageLine->text();
        QString dept = ui->deptLine->text();

        // ① 拼接发送给服务器端的数据
        QString params = QString("sname=%1&snickname=%2&sgender=%3&sage=%4&sdept=%5")
                .arg(name).arg(nickname).arg(gender).arg(age).arg(dept);
        // ② 准备request对象
        QNetworkRequest request;
        request.setUrl(QUrl("http://192.168.124.54:8088/school/api/v1.0/student"));
        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
        manager->post(request, params.toUtf8());
    });

}

AddForm::~AddForm()
{
    delete ui;
}
